<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { selectSysMachineInfoMachineIdListApi } from '@/api/system/monitor/SysMachineInfo'
import { KeyLabelValueVo } from '@/base/api/KeyLabelValueVo'
import { sysMachineLineChartApi } from '@/api/system/monitor/SysMachineReport'
import { ContentWrap } from '@/components/ContentWrap'
import { ElText, ElSelect, ElOption } from 'element-plus'
import CpuGaugeChart from '@/components/GaugeChart/src/GaugeChart.vue'

const machineList = ref<Array<KeyLabelValueVo>>([])
const initMachineList = async () => {
  const res = await selectSysMachineInfoMachineIdListApi({})
  machineList.value = res.data
  selectMachineId.value = res.data[0].label
  initChart()
  startInterval()
}
initMachineList()

const intervalId = ref<number>(null)
const startInterval = () => {
  intervalId.value = setInterval(() => {
    initChart()
  }, 10000)
}

onUnmounted(() => {
  clearInterval(intervalId.value)
})
const selectMachineId = ref('')

const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
const storageChartRef = ref(null)
const networkChartRef = ref(null)
const diskChartRef = ref(null)
const jvmChartRef = ref(null)

let cpuChart = null
let memoryChart = null
let storageChart = null
let networkChart = null
let diskChart = null
let jvmChart = null

const timeList = ref<Array<string>>([])
const cpuUsageData = ref<Array<number>>([])
const memoryUsageData = ref<Array<number>>([])
const storageUsageData = ref<Array<number>>([])
const uploadData = ref<Array<string>>([])
const downloadData = ref<Array<string>>([])
const diskReadData = ref<Array<string>>([])
const diskWriteData = ref<Array<string>>([])
const jvmUsageData = ref<Array<number>>([])

const cpuUsage = ref(0)
const memoryUsage = ref(0)

const initChart = async () => {
  const data = {
    machineId: selectMachineId.value
  }
  const res = await sysMachineLineChartApi(data)
  timeList.value = []
  cpuUsageData.value = []
  memoryUsageData.value = []
  storageUsageData.value = []
  uploadData.value = []
  downloadData.value = []
  diskReadData.value = []
  diskWriteData.value = []
  jvmUsageData.value = []

  res.data.forEach((item) => {
    cpuUsageData.value.push(item.cpuUsage)
    timeList.value.push(item.createTime!)
    memoryUsageData.value.push(item.memoryUsage)
    storageUsageData.value.push(item.storageUsage)
    uploadData.value.push(item.networkUploadShow)
    downloadData.value.push(item.networkDownloadShow)
    diskReadData.value.push(item.diskReadShow)
    diskWriteData.value.push(item.diskWriteShow)
    jvmUsageData.value.push(item.jvmMemoryUsage)
  })

  const latest = res.data[res.data.length - 1]
  cpuUsage.value = latest.cpuUsage
  memoryUsage.value = latest.memoryUsage

  // 数据获取后，渲染所有图表
  renderAllCharts()
}

// 在Vue组件中定义图表渲染函数
const renderAllCharts = () => {
  // 1. CPU利用率图表配置
  const cpuOption = {
    title: { text: 'CPU利用率趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '利用率 (%)',
      min: 0,
      max: 100,
      axisLabel: { formatter: '{value}%' }
    },
    series: [
      {
        name: 'CPU利用率',
        type: 'line',
        data: cpuUsageData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#c65454' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 2. 内存使用大小图表配置
  const memoryOption = {
    title: { text: '内存利用率趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '利用率 (%)',
      min: 0,
      max: 100,
      axisLabel: { formatter: '{value}%' }
    },
    series: [
      {
        name: '内存利用率',
        type: 'line',
        data: memoryUsageData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#91cc75' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 4. 存储使用大小图表配置
  const storageOption = {
    title: { text: '存储利用率趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '利用率 (%)',
      min: 0,
      max: 100,
      axisLabel: { formatter: '{value}%' }
    },
    series: [
      {
        name: '存储利用率',
        type: 'line',
        data: storageUsageData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#66cab3' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 4. 网络流量图表配置（上行和下行在一个图中显示）
  const networkOption = {
    title: { text: '网络流量趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['网络上行', '网络下行'], right: 10 },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '流量 (KBps)',
      axisLabel: { formatter: '{value} KBps' }
    },
    series: [
      {
        name: '网络上行',
        type: 'line',
        data: uploadData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#fac858' }
      },
      {
        name: '网络下行',
        type: 'line',
        data: downloadData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#48a2ec' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 5. 磁盘读写图表配置（读取和写入在一个图中显示）
  const diskOption = {
    title: { text: '硬盘读写趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['硬盘读取', '硬盘写入'], right: 10 },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '读写速度 (KBps)',
      axisLabel: { formatter: '{value} KBps' }
    },
    series: [
      {
        name: '硬盘读取',
        type: 'line',
        data: diskReadData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#fa58b9' }
      },
      {
        name: '硬盘写入',
        type: 'line',
        data: diskWriteData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#a2ec48' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 6. jvm使用大小图表配置
  const jvmOption = {
    title: { text: 'jvm内存利用率趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: timeList.value
    },
    yAxis: {
      type: 'value',
      name: '利用率 (%)',
      min: 0,
      max: 100,
      axisLabel: { formatter: '{value}%' }
    },
    series: [
      {
        name: 'jvm内存利用率',
        type: 'line',
        data: jvmUsageData.value,
        smooth: true,
        lineStyle: { width: 2 },
        itemStyle: { color: '#ccb875' }
      }
    ],
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }
  }

  // 初始化并渲染图表
  if (cpuChartRef.value) {
    if (cpuChart) {
      cpuChart.dispose() // 销毁已有实例
    }
    cpuChart = echarts.init(cpuChartRef.value)
    cpuChart.setOption(cpuOption)
  }

  if (memoryChartRef.value) {
    if (memoryChart) {
      memoryChart.dispose()
    }
    memoryChart = echarts.init(memoryChartRef.value)
    memoryChart.setOption(memoryOption)
  }

  if (storageChartRef.value) {
    if (storageChart) {
      storageChart.dispose()
    }
    storageChart = echarts.init(storageChartRef.value)
    storageChart.setOption(storageOption)
  }

  if (networkChartRef.value) {
    if (networkChart) {
      networkChart.dispose()
    }
    networkChart = echarts.init(networkChartRef.value)
    networkChart.setOption(networkOption)
  }

  if (diskChartRef.value) {
    if (diskChart) {
      diskChart.dispose()
    }
    diskChart = echarts.init(diskChartRef.value)
    diskChart.setOption(diskOption)
  }

  if (jvmChartRef.value) {
    if (jvmChart) {
      jvmChart.dispose()
    }
    jvmChart = echarts.init(jvmChartRef.value)
    jvmChart.setOption(jvmOption)
  }
}

// 在组件挂载时获取数据并初始化图表
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  const charts = [cpuChart]
  charts.forEach((chart) => {
    if (chart) {
      chart.resize()
    }
  })
}

// 在组件卸载时销毁图表实例
onUnmounted(() => {
  const charts = [cpuChart]
  charts.forEach((chart) => {
    if (chart) {
      chart.dispose()
    }
  })
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <ContentWrap>
    <div class="server-info">
      <div>
        <el-text type="primary" size="large">服务器信息</el-text>
      </div>

      <el-select
        v-model="selectMachineId"
        placeholder="请选择服务器"
        @change="initChart"
        class="select-machine-id"
      >
        <el-option v-for="item in machineList" :key="item.label" :value="item.label">
          {{ item.label }}
        </el-option>
      </el-select>
    </div>

    <div class="monitor-dashboard">
      <div class="chart-container">
        <CpuGaugeChart :cpu-usage="cpuUsage" :title="'CPU利用率'" />
      </div>

      <div class="chart-container">
        <CpuGaugeChart :cpu-usage="memoryUsage" :title="'内存利用率'" />
      </div>

      <!-- CPU利用率图表 -->
      <div class="chart-container">
        <div ref="cpuChartRef" class="chart"></div>
      </div>

      <!-- 内存使用大小图表 -->
      <div class="chart-container">
        <div ref="memoryChartRef" class="chart"></div>
      </div>

      <div class="chart-container">
        <div ref="storageChartRef" class="chart"></div>
      </div>

      <!-- 网络流量图表（上行+下行，可以放在一个图中） -->
      <div class="chart-container">
        <div ref="networkChartRef" class="chart"></div>
      </div>

      <div class="chart-container">
        <div ref="diskChartRef" class="chart"></div>
      </div>

      <div class="chart-container">
        <div ref="jvmChartRef" class="chart"></div>
      </div>
    </div>
  </ContentWrap>
</template>

<style scoped lang="less">
.server-info {
  margin-bottom: 20px;
  padding-left: 15px;
  padding-right: 15px;
}

.select-machine-id {
  margin-top: 15px;
  width: 300px;
}

.monitor-dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  padding: 20px;
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 400px; /* 给图表一个固定的高度 */
}

@media (max-width: 768px) {
  .monitor-dashboard {
    grid-template-columns: 1fr;
  }
}
</style>
